document.addEventListener('DOMContentLoaded', function() {
    const modSingerList = document.querySelector('.mod_singer_list');
    const singerListText = document.querySelector('.singer_list_text');
    const filterLinks = document.querySelectorAll('.filter-link');
    let pageNo = 1;
    let area = '-100';
    let genre = '-100';
    let index = '-100';
    let sex = '-100';

    function loadSingers(reset = false) {
        if (reset) {
            pageNo = 1;
            modSingerList.innerHTML = '';
            singerListText.innerHTML = '';
        }

        fetch(`http://127.0.0.1:5000/singer/list?pageNo=${pageNo}&area=${area}&genre=${genre}&index=${index}&sex=${sex}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then(data => {
                if (data.result !== 100) {
                    throw new Error('API response error: ' + data.result);
                }
                const singers = data.data.list;
                singers.forEach((singer, i) => {
                    if (i + ((pageNo - 1) * 20) < 10) {
                        const singerItem = document.createElement('div');
                        singerItem.classList.add('singer-item');
                        singerItem.innerHTML = `
                            <a href="/singer_detail?singer_id=${singer.singer_mid}">
                                <img src="${singer.singer_pic}" alt="${singer.singer_name}">
                                <p>${singer.singer_name}</p>
                            </a>
                        `;
                        modSingerList.appendChild(singerItem);
                    } else {
                        const singerTxtItem = document.createElement('li');
                        singerTxtItem.classList.add('singer_list_txt_item');
                        singerTxtItem.innerHTML = `
                            <a class="singer_list_txt_link js_singer" title="${singer.singer_name}" href="/singer_detail?singer_id=${singer.singer_mid}">${singer.singer_name}</a>
                        `;
                        singerListText.appendChild(singerTxtItem);
                    }
                });
                pageNo++;
            })
            .catch(error => {
                console.error('Error fetching singer list:', error);
            });
    }

    function handleScroll() {
        if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 2) {
            loadSingers();
        }
    }

    function handleFilterClick(event) {
        event.preventDefault();
        const type = event.target.getAttribute('data-type');
        const value = event.target.getAttribute('data-value');

        if (type === 'area') {
            area = value;
        } else if (type === 'genre') {
            genre = value;
        } else if (type === 'index') {
            index = value;
        } else if (type === 'sex') {
            sex = value;
        }

        filterLinks.forEach(link => {
            if (link.getAttribute('data-type') === type) {
                link.classList.remove('active');
            }
        });

        event.target.classList.add('active');
        loadSingers(true);
    }

    filterLinks.forEach(link => {
        link.addEventListener('click', handleFilterClick);
    });

    window.addEventListener('scroll', handleScroll);

    loadSingers();  // 初次加载
});

document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const singerMid = urlParams.get('singer_id');
    const userId = '969359586'; // QQ号

    if (!singerMid) {
        console.error('No singer_id found in URL');
        return;
    }

    const moreBtn = document.getElementById('moreBtn');
    const bioModal = document.getElementById('bioModal');
    const closeBtn = document.getElementById('closeBtn');
    const fullBio = document.getElementById('fullBio');
    const singerNameElement = document.getElementById('singerName');
    const singerImageElement = document.getElementById('singerImage');
    const singerBioElement = document.getElementById('singerBio');
    const songListElement = document.getElementById('songList');
    const albumListElement = document.getElementById('albumList');
    const mvListElement = document.getElementById('mvList');
    const songButton = document.getElementById('songButton');
    const albumButton = document.getElementById('albumButton');
    const mvButton = document.getElementById('mvButton');
    const songSection = document.getElementById('songSection');
    const albumSection = document.getElementById('albumSection');
    const mvSection = document.getElementById('mvSection');
    const lyricsModal = document.getElementById('lyrics-modal');
    const lyricsContent = document.getElementById('lyrics-content');
    const closeLyricsBtn = document.getElementById('close-lyrics');
    const musicPlayer = document.getElementById('music-player');
    const albumCover = document.getElementById('album-cover');
    const songNameElement = document.getElementById('song-name');
    const singerNameElementPlayer = document.getElementById('singer-name');
    const playButton = document.getElementById('play-button');
    const prevButton = document.getElementById('prev-button');
    const nextButton = document.getElementById('next-button');
    const lyricsButton = document.getElementById('lyrics-button');
    const playModeButton = document.getElementById('play-mode');
    const mvModal = document.getElementById('mvModal');
    const mvPlayer = document.getElementById('mvPlayer');
    const closeMvBtn = document.getElementById('closeMvBtn');
    const progressBar = document.getElementById('progress-bar');
    const currentTimeElement = document.getElementById('current-time');
    const totalTimeElement = document.getElementById('total-time');
    const currentLyricElement = document.getElementById('current-lyric');
    let isSeeking = false;
    let parsedLyrics = [];

    let songPageNo = 1;
    let albumPageNo = 1;
    let mvPageNo = 1;
    let audio = null;
    let playMode = 'sequence'; // 'sequence', 'shuffle', 'repeat'
    let currentSongMid = null;
    let playList = [];
    let currentSongIndex = -1;

    const baseURL = 'http://127.0.0.1:5000';

    closeMvBtn.addEventListener('click', function() {
        mvModal.style.display = 'none';
        mvPlayer.src = '';
    });

    function setUserCookie(cookieData) {
        return fetch(`${baseURL}/user/setCookie`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ data: cookieData }),
            credentials: 'include'
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                throw new Error(data.error);
            }
            console.log('Cookie set successfully:', data);
        })
        .catch(error => console.error('Error setting user cookie:', error));
    }

    const exampleCookieData = 'your_cookie_data_here';
    setUserCookie(exampleCookieData);

    function fetchSingerDesc() {
        fetch(`${baseURL}/singer/desc?singermid=${singerMid}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error(data.error);
                    return;
                }
                const singerDesc = data.data.desc.substring(0, 100) + '...';
                fullBio.textContent = data.data.desc;
                singerImageElement.src = `http://y.gtimg.cn/music/photo_new/T001R150x150M000${singerMid}.webp`;
                singerBioElement.innerHTML = `${singerDesc} <span class="more-btn" id="moreBtn">更多</span>`;
                document.getElementById('moreBtn').addEventListener('click', function() {
                    bioModal.style.display = 'block';
                });
            })
            .catch(error => console.error('Error fetching singer description:', error));
    }

    function fetchSingerName(singerMid) {
        fetch(`${baseURL}/singer/list?pageNo=1&area=-100&genre=-100&index=-100&sex=-100`)
            .then(response => response.json())
            .then(data => {
                if (data.result !== 100) {
                    throw new Error('API response error: ' + data.result);
                }
                const singers = data.data.list;
                const singer = singers.find(singer => singer.singer_mid === singerMid);
                if (singer) {
                    singerNameElement.textContent = singer.singer_name || 'Unknown';
                } else {
                    console.error('Singer not found');
                }
            })
            .catch(error => console.error('Error fetching singer name:', error));
    }

    function fetchSingerSongs(reset = false) {
    if (reset) {
        songPageNo = 1;
        songListElement.innerHTML = '';
        playList = []; // 重置播放列表
        currentSongIndex = 0; // 重置当前播放的歌曲索引
    }
    fetch(`${baseURL}/singer/songs?singermid=${singerMid}&page=${songPageNo}&num=20`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                console.error(data.error);
                return;
            }
            const songs = data.data.list;
            songs.forEach(song => {
                playList.push(song.mid); // 添加歌曲到播放列表
                const songItem = document.createElement('li');
                songItem.classList.add('song-item');
                const albumCoverUrl = `http://y.gtimg.cn/music/photo_new/T002R300x300M000${song.album.mid}.jpg`;
                const singerName = song.singer[0].name;
                songItem.innerHTML = `
                    <img src="${albumCoverUrl}" alt="Album Cover" class="song-album-cover">
                    <div class="songlist_songname">${song.name}</div>
                    <div class="songlist_album">${song.album.title}</div>
                    <div class="songlist_time">${formatTime(song.interval)}</div>
                    <button class="play-button" data-songmid="${song.mid}" data-songname="${song.name}" data-singername="${singerName}" data-albumcover="${albumCoverUrl}">播放</button>
                `;
                songListElement.appendChild(songItem);
            });
            addPlayButtonEventListeners();
            songPageNo++;
        })
        .catch(error => console.error('Error fetching singer songs:', error));
}

    function fetchSingerAlbums(reset = false) {
        if (reset) {
            albumPageNo = 1;
            albumListElement.innerHTML = '';
        }
        fetch(`${baseURL}/singer/album?singermid=${singerMid}&pageNo=${albumPageNo}&pageSize=20`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error(data.error);
                    return;
                }
                const albums = data.data.list;
                albums.forEach(album => {
                    const albumItem = document.createElement('div');
                    albumItem.classList.add('album-item');
                    albumItem.innerHTML = `
                        <img src="http://y.gtimg.cn/music/photo_new/T002R300x300M000${album.album_mid}.jpg" alt="Album Image">
                        <p>${album.album_name}</p>
                    `;
                    albumListElement.appendChild(albumItem);
                });
                albumPageNo++;
            })
            .catch(error => console.error('Error fetching singer albums:', error));
    }

    function fetchSingerMvs(reset = false) {
        if (reset) {
            mvPageNo = 1;
            mvListElement.innerHTML = '';
        }
        fetch(`${baseURL}/singer/mv?singermid=${singerMid}&pageNo=${mvPageNo}&pageSize=20`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error(data.error);
                    return;
                }
                const mvs = data.data.list;
                mvs.forEach(mv => {
                    const mvItem = document.createElement('div');
                    mvItem.classList.add('mv-item');
                    mvItem.innerHTML = `
                        <img src="${mv.pic}" alt="MV Image">
                        <p>${mv.title}</p>
                    `;
                    mvItem.addEventListener('dblclick', function() {
                        playMv(mv.vid);
                    });
                    mvListElement.appendChild(mvItem);
                });
                mvPageNo++;
            })
            .catch(error => console.error('Error fetching singer MVs:', error));
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60; // 取整后的秒数
        return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    }

    function addPlayButtonEventListeners() {
        const playButtons = document.querySelectorAll('.play-button');
        playButtons.forEach(button => {
            button.addEventListener('click', function() {
                const songMid = this.getAttribute('data-songmid');
                const songName = this.getAttribute('data-songname');
                const singerName = this.getAttribute('data-singername');
                const albumCover = this.getAttribute('data-albumcover');

                currentSongIndex = playList.indexOf(songMid); // 更新当前播放的歌曲索引
                currentSongMid = songMid; // 保存当前播放的songmid

                fetch(`${baseURL}/user/refresh`, { method: 'GET', credentials: 'include' })
                    .then(() => fetchPlayUrl(songMid))
                    .then(songUrl => {
                        if (songUrl) {
                            updatePlayer(songUrl, songName, singerName, albumCover);
                            playSong(songUrl);
                            // 获取歌词并解析
                            fetchLyrics(songMid)
                                .then(lyrics => {
                                    parsedLyrics = parseLyrics(lyrics);
                                })
                                .catch(error => console.error('Error fetching lyrics:', error));
                        } else {
                            console.error('无法获取播放链接');
                        }
                    })
                    .catch(error => console.error('Error:', error));
            });
        });
    }

    function fetchPlayUrl(songMid) {
        return fetch(`${baseURL}/song/url?id=${songMid}`, {
            method: 'GET',
            credentials: 'include'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.result !== 100) {
                throw new Error('API response error: ' + data.result);
            }
            return data.data;
        })
        .catch(error => console.error('Error fetching play URL:', error));
    }

   function playSong(url) {
    if (audio) {
        audio.pause();
    }
    audio = new Audio(url);
    audio.play()
        .then(() => {
            musicPlayer.style.display = 'flex';
            setTimeout(() => {
                musicPlayer.style.opacity = 1;
            }, 10);
            playButton.textContent = '⏸️';
            updateProgressBar(); // 更新进度条

            audio.addEventListener('ended', function() {
                if (playMode === 'repeat') {
                    playCurrentSong();
                } else {
                    nextButton.click();
                }
            });
        })
        .catch(error => console.error('Error playing song:', error));
}

    function playMv(vid) {
        const mvUrl = `https://y.qq.com/n/ryqq/mv/${vid}`;
        mvPlayer.src = mvUrl;
        mvModal.style.display = 'block';
    }

    function updatePlayer(url, songName, singerName, albumCoverUrl) {
        albumCover.src = albumCoverUrl;
        songNameElement.textContent = songName;
        singerNameElementPlayer.textContent = singerName;
        musicPlayer.style.display = 'flex';
        setTimeout(() => {
            musicPlayer.style.opacity = 1;
        }, 10);
    }

    function fetchLyrics(songMid) {
        return fetch(`${baseURL}/lyric?songmid=${songMid}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                return data.data.lyric;
            });
    }

    function parseLyrics(lyrics) {
        const lines = lyrics.split('\n');
        const parsedLyrics = [];
        const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2})\]/;

        lines.forEach(line => {
            const timeMatch = line.match(timeRegex);
            if (timeMatch) {
                const minutes = parseInt(timeMatch[1], 10);
                const seconds = parseInt(timeMatch[2], 10);
                const milliseconds = parseInt(timeMatch[3], 10);
                const time = minutes * 60 + seconds + milliseconds / 1000;
                const text = line.replace(timeRegex, '').trim();
                parsedLyrics.push({ time, text });
            }
        });

        return parsedLyrics;
    }

    function showLyrics(lyrics) {
        lyricsContent.innerHTML = lyrics.replace(/\n/g, '<br>');
        lyricsModal.style.display = 'block';
    }

    function updateCurrentLyric(currentTime) {
        if (!parsedLyrics || parsedLyrics.length === 0) return;

        let currentLyric = '';
        for (let i = 0; i < parsedLyrics.length; i++) {
            if (currentTime >= parsedLyrics[i].time) {
                currentLyric = parsedLyrics[i].text;
            } else {
                break;
            }
        }

        if (currentLyric !== currentLyricElement.textContent) {
            currentLyricElement.style.opacity = 0;
            setTimeout(() => {
                currentLyricElement.textContent = currentLyric;
                currentLyricElement.style.opacity = 1;
            }, 500); // 渐变时间
        }
    }

    function updateProgressBar() {
        if (audio && !isSeeking) {
            progressBar.max = Math.floor(audio.duration); // 取整
            progressBar.value = Math.floor(audio.currentTime); // 取整
            currentTimeElement.textContent = formatTime(Math.floor(audio.currentTime));
            totalTimeElement.textContent = formatTime(Math.floor(audio.duration));

            // 更新当前歌词
            updateCurrentLyric(Math.floor(audio.currentTime));
        }
        requestAnimationFrame(updateProgressBar);
    }

    progressBar.addEventListener('input', function() {
        isSeeking = true;
        currentTimeElement.textContent = formatTime(Math.floor(progressBar.value));
    });

    progressBar.addEventListener('change', function() {
        isSeeking = false;
        if (audio) {
            audio.currentTime = Math.floor(progressBar.value); // 取整
        }
    });

    playButton.addEventListener('click', function() {
        if (audio) {
            if (audio.paused) {
                audio.play();
                playButton.textContent = '⏸️';
                musicPlayer.style.opacity = 1;
            } else {
                audio.pause();
                playButton.textContent = '▶️';
                musicPlayer.style.opacity = 1; // 保持播放器显示
            }
        }
    });

    nextButton.addEventListener('click', function() {
    if (playMode === 'shuffle') {
        currentSongIndex = Math.floor(Math.random() * playList.length);
    } else {
        currentSongIndex = (currentSongIndex + 1) % playList.length;
    }
    playCurrentSong();
});

prevButton.addEventListener('click', function() {
    if (playMode === 'shuffle') {
        currentSongIndex = Math.floor(Math.random() * playList.length);
    } else {
        currentSongIndex = (currentSongIndex - 1 + playList.length) % playList.length;
    }
    playCurrentSong();
});


    function playCurrentSong() {
    const songMid = playList[currentSongIndex];
    currentSongMid = songMid;  // 更新当前播放的歌曲ID
    fetchSongDetails(songMid)
        .then(details => {
            fetch(`${baseURL}/user/refresh`, { method: 'GET', credentials: 'include' })
                .then(() => fetchPlayUrl(songMid))
                .then(songUrl => {
                    if (songUrl) {
                        updatePlayer(songUrl, details.name, details.singer, details.albumCover);
                        playSong(songUrl);
                        fetchLyrics(songMid)
                            .then(lyrics => {
                                parsedLyrics = parseLyrics(lyrics);
                                updateCurrentLyric(0); // 确保歌词从头开始显示
                            })
                            .catch(error => console.error('Error fetching lyrics:', error));
                    } else {
                        console.error('无法获取播放链接');
                    }
                })
                .catch(error => console.error('Error:', error));
        });
}

    function fetchSongDetails(songMid) {
        // 根据之前的代码获取歌曲的详细信息
        return fetch(`${baseURL}/singer/songs?singermid=${singerMid}&num=20`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                const song = data.data.list.find(song => song.mid === songMid);
                return {
                    name: song.name,
                    singer: song.singer[0].name,
                    albumCover: `http://y.gtimg.cn/music/photo_new/T002R300x300M000${song.album.mid}.jpg`
                };
            });
    }

    lyricsButton.addEventListener('click', function() {
    if (currentSongMid) {
        fetchLyrics(currentSongMid)
            .then(lyrics => {
                showLyrics(lyrics);  // 重新显示歌词
                parsedLyrics = parseLyrics(lyrics);  // 更新实时歌词
            })
            .catch(error => console.error('Error fetching lyrics:', error));
    } else {
        console.error('没有找到当前播放的歌曲ID');
    }
});

    closeLyricsBtn.addEventListener('click', function() {
        lyricsModal.style.display = 'none';
    });

    songButton.addEventListener('click', function() {
        songSection.style.display = 'block';
        albumSection.style.display = 'none';
        mvSection.style.display = 'none';
        fetchSingerSongs(true);
    });

    albumButton.addEventListener('click', function() {
        albumSection.style.display = 'block';
        songSection.style.display = 'none';
        mvSection.style.display = 'none';
        fetchSingerAlbums(true);
    });

    mvButton.addEventListener('click', function() {
        mvSection.style.display = 'block';
        songSection.style.display = 'none';
        albumSection.style.display = 'none';
        fetchSingerMvs(true);
    });

    playModeButton.addEventListener('click', function() {
    if (playMode === 'sequence') {
        playMode = 'shuffle';
        playModeButton.textContent = '🔀';
    } else if (playMode === 'shuffle') {
        playMode = 'repeat';
        playModeButton.textContent = '🔂';
    } else {
        playMode = 'sequence';
        playModeButton.textContent = '🔁';
    }
});


    moreBtn.addEventListener('click', function() {
        bioModal.style.display = 'block';
    });

    closeBtn.addEventListener('click', function() {
        bioModal.style.display = 'none';
    });

    window.addEventListener('click', function(event) {
        if (event.target === bioModal) {
            bioModal.style.display = 'none';
        }
        if (event.target === lyricsModal) {
            lyricsModal.style.display = 'none';
        }
    });

    window.addEventListener('scroll', function() {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 2) {
            if (songSection.style.display === 'block') {
                fetchSingerSongs();
            } else if (albumSection.style.display === 'block') {
                fetchSingerAlbums();
            } else if (mvSection.style.display === 'block') {
                fetchSingerMvs();
            }
        }
    });

    setUserCookie()
        .then(() => {
            fetchSingerDesc();
            fetchSingerName(singerMid);
            fetchSingerSongs();
        })
        .catch(error => console.error('Error setting user cookie:', error));
});
